package com.atguigu.activemq.jdbc_persistent.queue;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQMessageProducer;
import org.apache.activemq.AsyncCallback;

import javax.jms.*;
import java.util.UUID;

public class JmsProduce {
    public static final String ACTIVEMQ_URL="tcp://124.70.84.192:61616";
    public static final String QUEUE_NAME="queue_jdbc";
    public static void main(String[] args) throws JMSException {
        ActiveMQConnectionFactory activeMQConnectionFactory=new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        activeMQConnectionFactory.setUseAsyncSend(true);//开启异步投递
        Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(QUEUE_NAME);
        ActiveMQMessageProducer activeMQMessageProducer = (ActiveMQMessageProducer)session.createProducer(queue);
        activeMQMessageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);//一定要设置持久化
        //将MessageProducer类型强转为ActiveMQMessageProducer类型
        for (int i=1;i<4;i++){
            TextMessage textMessage = session.createTextMessage("我发送的第" + i + "条消息");
            textMessage.setJMSMessageID(UUID.randomUUID().toString()+"--atguigu");
            //消息头设置一个JMSMessageID
            String msgid = textMessage.getJMSMessageID();
            activeMQMessageProducer.send(textMessage, new AsyncCallback() {
                //2个形参的send()方法
                @Override//消息发送成功了怎样
                public void onSuccess() {
                    System.out.println(msgid+"：发送成功");
                }

                @Override//消息发送失败了怎样
                public void onException(JMSException e) {
                    System.out.println(msgid+"：发送失败");
                }
            });
        }
        activeMQMessageProducer.close();
        session.close();
        connection.close();
        System.out.println("连接中断");
    }
}
